<template>
  <div>
    <div id="tools">
      <!--停车场管理-->
      <div class="height8"></div>
      <!-- 查询条件 -->
      <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">

        <a-form-item label="关键字" class="marginBtm">
          <a-input v-model="queryValue" allowClear placeholder="请输入用户名" class="marginBtm"
                   @pressEnter="inquireStart"/>
        </a-form-item>

        <a-form-item class="marginBtm">
          <a-button type="primary" @click="inquireStart">
            查询
          </a-button>
        </a-form-item>

      </a-form>
      <a-divider style="margin: 5px 0"/>
      <div style="padding: 5px 10px 10px 10px;text-align: left;">
        <a-button type="primary" class="button-marin" @click="addDilog">
          新增
        </a-button>
        <a-button type="primary" class="button-marin" @click="modifyDilog">
          修改
        </a-button>
        <a-button type="primary" class="button-marin" @click="dateleUser">
          删除
        </a-button>
      </div>
    </div>

    <a-table
      class="tabled"
      bordered
      :fixed="true"
      size="small"
      :columns="columns"
      :row-key="record => record.id"
      :rowSelection="{type:'radio',selectedRowKeys:selectedRowKeys,fixed:true,onChange:onChange}"
      :customRow="clickRow"
      :data-source="tableData"
      :pagination="pagination"
      :loading="loading"
      :scroll="{ x:xWidth,y: yHeight }"
      :locale="localezh_CN"
      @change="handleTableChange"
    >
      <!--点击行选中行，点击单选按钮选中行；但是需要:row-key是唯一标示字段-->

      <!-- <template slot="name" slot-scope="name"> {{ name.first }} {{ name.last }} </template> -->
    </a-table>
    <!--新增修改弹窗-->
    <collection-admin-definition-form
      ref="collectionAdminDefinitionForm"
      :visible="visible"
      :title="modalTitle"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      @create="handleCreate"
    />
  </div>
</template>

<script>
import { tableBoxHeight } from '@/api/communal'
import adminDefinitionApi from '@/api/adminDefinition'
// eslint-disable-next-line camelcase
import localezh_CN from 'antd/lib/locale-provider/zh_CN'
// eslint-disable-next-line no-unused-vars
import { ConfigProvider } from 'ant-design-vue'// 引用
import 'moment/locale/zh-cn'
import CollectionAdminDefinitionForm from '@/components/adminDefinitionForm'

export default {
  components: {
    // eslint-disable-next-line vue/no-unused-components
    ConfigProvider,
    CollectionAdminDefinitionForm
  },
  name: '',
  data () {
    return {
      localezh_CN,
      spinning: false,
      importVisible: false,
      importLoading: false,
      fileList: [],
      errorMessage: '',
      carstype: [],
      delayTime: 500,
      confirmLoading: false,
      modalData: null,
      xWidth: '',
      yHeight: '',
      tableData: [],
      modalTitle: '新增',
      pagination: {
        pageSize: 30,
        current: 1,
        total: 100,
        showSizeChanger: true,
        // showQuickJumper: true,
        pageSizeOptions: ['30', '50', '100'],
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => {
          // console.log("1111");
          this.pagination.current = 1
          this.pagination.pageSize = pageSize
        }
      },
      selectedRowKeys: [],
      selectedRows: null,
      loading: false,
      queryValue: '', // 查询值,访客名称，访客手机号
      columns: [], // 表格表头
      visible: false
    }
  },

  beforeMount: function () {
    this.columns = [
      {
        title: '序号', // 表头
        dataIndex: 'serialNumber', // 字段名称
        width: '50px', // 设列宽度
        align: 'center', // 居中显示
        className: 'changeBack', // 重置覆盖背景色为浅灰色，否则是白色的
        customRender: (value, row, index) => `${(this.pagination.current - 1) * this.pagination.pageSize + index + 1}` // 设置动态序号
      },
      {
        title: '用户名',
        dataIndex: 'account',
        width: '100px',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '真实姓名',
        dataIndex: 'name',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '电话',
        dataIndex: 'phone',
        width: '100px',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        width: '150px',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '权限组',
        dataIndex: 'authorityName',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '创建人',
        dataIndex: 'creationUser',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '创建时间',
        dataIndex: 'creationTime',
        width: '150px',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '修改人',
        dataIndex: 'updateUser',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
        width: '150px',
        align: 'center',
        className: 'changeBack'
      },
      {
        title: '操作',
        dataIndex: '',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      }
    ]
  },
  mounted () {
    this.yHeight = tableBoxHeight() + 3 + 'px'
    this.xWidth = this.getTableWidth()
    const minHeight = document.getElementsByClassName('ant-table')
    minHeight[0].style.minHeight = tableBoxHeight() + 40 + 'px'
    this.inquireStart()
  },
  methods: {
    // 计算表格宽度
    getTableWidth () {
      let totals = null
      var el
      for (el of this.columns) {
        totals += parseInt(el.width)
      }
      return totals + 100 + 'px'
    },
    // 删除
    async dateleUser () {
      if (this.selectedRows) {
        const param = {
          id: this.selectedRows.id
        }
        const resp = await adminDefinitionApi.deleteUser(param)
        console.log(resp.data)
        if (resp.data.success) {
          this.confirmLoading = false // 提交按钮加载中
          this.$refs.collectionAdminDefinitionForm.initFormValue()
          this.visible = false // 关闭弹窗
          this.$message.success('删除成功')
          this.inquireStart()
        } else {
          this.confirmLoading = false // 提交按钮加载中
          this.$message.error(resp.data.message)
        }
      }else{
        this.$message.warning('请选择要进行删除的数据')
      }
    },
    // 开始查询
    inquireStart () {
      this.pagination.current = 1
      this.selectedRowKeys = []
      this.selectedRows = null
      // 如果增加查询条件，导出里面也要增加，条件一样
      const param = {
        current: this.pagination.current,
        pageSize: this.pagination.pageSize,
        serchTxt: this.queryValue
      }
      // console.log(param);
      this.fetch(param)
    },
    // 点击行
    clickRow (record) {
      return {
        on: {
          click: () => {
            console.log(record)
            const keys = []
            keys.push(record.id) // 行数据一定要有唯一识别标志，否则无法选中，和表格的key一致
            this.selectedRowKeys = keys
            this.selectedRows = record
          }
        }
      }
    },
    // 表格切换分页
    handleTableChange (pagination, filters, sorter) {
      // console.log(pagination);
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.fetch({
        pageSize: pagination.pageSize,
        current: pagination.current,
        serchTxt: this.queryValue,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      })
    },
    // 新增弹窗
    addDilog () {
      console.log(this.selectedRows) // 行数据
      this.modalTitle = '新增'
      // 如果有行数据，就填充到弹窗中，没有则不处理
      if (this.selectedRows) {
        this.visible = true
        this.$nextTick(() => {
          this.$refs.collectionAdminDefinitionForm.stuffDilog(null, false)
        })
      } else {
        this.visible = true
      }
    },
    // 修改弹窗
    modifyDilog () {
      // 如果有行数据，就填充到弹窗中，如果为null，则提示选一个人，修改时要考虑是否有些东西是不可修改的，如果没有，可以和新增共用一个方法
      console.log(this.selectedRows) // 行数据
      this.modalTitle = '修改'
      if (this.selectedRows) {
        this.visible = true
        this.$nextTick(() => {
          this.$refs.collectionAdminDefinitionForm.stuffDilog(this.selectedRows, true)
        })
      } else {
        this.$message.warning('请选择要进行修改的数据')
      }
    },
    async handleOk () {
      console.log(this.modalData) // 弹窗数据
      // 判断2次密码是否一样
      // eslint-disable-next-line eqeqeq
      if (this.modalData.password != this.modalData.qrPassword) {
        this.$message.warning('2次密码不一致')
        return false
      }
      this.confirmLoading = true // 提交按钮加载中
      // 处理提交事件
      const params = {
        account: this.modalData.account,
        name: this.modalData.name,
        phone: this.modalData.phone,
        email: this.modalData.email,
        password: this.modalData.password,
        authorityId: this.modalData.authorityId,
        bz: this.modalData.bz,
        // eslint-disable-next-line eqeqeq
        id: this.modalTitle == '新增' ? 0 : this.selectedRows.id // 大于0修改，小于0添加
      }
      console.log(params)
      const resp = await adminDefinitionApi.savaUser(params)
      console.log(resp.data)
      if (resp.data.success) {
        this.confirmLoading = false // 提交按钮加载中
        this.$refs.collectionAdminDefinitionForm.initFormValue()
        this.visible = false // 关闭弹窗
        this.$message.success('保存成功')
        this.inquireStart()
      } else {
        this.confirmLoading = false // 提交按钮加载中
        this.$message.error(resp.data.message)
      }
    },
    handleCancel () {
      this.$refs.collectionAdminDefinitionForm.initFormValue()
      this.confirmLoading = false // 提交按钮加载中
      this.visible = false
    },

    handleCreate () {
      const _this = this
      const form = this.$refs.collectionAdminDefinitionForm.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        console.log(values)
        this.modalData = values
        _this.handleOk()
      })
    },

    onChange (selectedRowKeys, selectedRows) {
      console.log(selectedRowKeys, selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows[0]
    },
    // 请求表格数据
    async fetch (params) {
      this.loading = true
      const resp = await adminDefinitionApi.getUserList(params)
      console.log(resp.data)
      if (resp.data.success) {
        this.loading = false
        this.pagination.total = resp.data.result.total
        this.tableData = resp.data.result.records
      } else {
        this.loading = false
        this.$message.error(resp.data.message)
      }
    },
    beforeUpload (file) {
      // console.log(file);
    },
    handleChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // console.log(info.file.response.result);
          if (info.file.response.result.length > 0) {
            this.errorMessage = info.file.response.result[0].errorMsg
          } else {
            this.$message.success(`${info.file.name}`) // 导入成功
            this.importVisible = false
            this.inquireStart()
          }
        } else {
          this.errorMessage = info.file.response.message
          // this.$message.error(`${info.file.response.message}`);
        }
      } else if (info.file.status === 'error') {
        // this.$message.error(`${info.file.name}`);
        this.errorMessage = info.file.name
      }
    },
    importCancel () {
      this.importVisible = false
    }

  }
}
</script>

<style scoped>
.marginBtm {
  margin-bottom: 5px;
}

</style>
